package com.ovolucky.mapmytrip.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.ovolucky.mapmytrip.app.storage.TripStore;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.ovolucky.mapmytrip.app.CreateMarkerActivity.DESCRIPTION_KEY;
import static com.ovolucky.mapmytrip.app.CreateMarkerActivity.TITLE_KEY;

/**
 * A placeholder fragment containing a simple view.
 */
public class MapContainerFragment extends MapFragment {

  public static final int CREATE_MARKER = 100;
  public static final String LATITUDE = "latitude";
  public static final String LONGITUDE = "longtitude";

  /**
   * The fragment argument representing the section number for this
   * fragment.
   */
  private static final String TRIP_ID = "trip_id";
  private GoogleMap map;
  private TripStore tripStore;

  /**
   * Returns a new instance of this fragment for the given section
   * number.
   */
  public static MapContainerFragment newInstance(long tripId) {
    MapContainerFragment fragment = new MapContainerFragment();
    Bundle args = new Bundle();
    args.putLong(TRIP_ID, tripId);
    fragment.setArguments(args);
    return fragment;
  }

  public MapContainerFragment() {
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    tripStore = new TripStore(getActivity());
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    initializeMap();
    return rootView;
  }

  private void initializeMap() {
    map = getMap();
    map.setMyLocationEnabled(true);
    map.setTrafficEnabled(true);
    UiSettings settings = map.getUiSettings();
    settings.setMyLocationButtonEnabled(true);
    settings.setCompassEnabled(true);
    settings.setAllGesturesEnabled(true);
    settings.setZoomControlsEnabled(true);

    // Add map click listener.
    map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
      @Override
      public void onMapLongClick(LatLng latLng) {
        Intent intent = new Intent(getActivity(), CreateMarkerActivity.class);
        intent.putExtra(LATITUDE, latLng.latitude);
        intent.putExtra(LONGITUDE, latLng.longitude);
        startActivityForResult(intent, CREATE_MARKER);
      }
    });

    List<Double> latitudes = new ArrayList<>();
    List<Double> longitudes = new ArrayList<>();
    List<MarkerOptions> allMarkers =
        tripStore.getAllMarkers(getArguments().getLong(TRIP_ID));
    for (MarkerOptions options : allMarkers) {
      map.addMarker(options);
      LatLng position = options.getPosition();
      latitudes.add(position.latitude);
      longitudes.add(position.longitude);
    }

    // Calculate bound for all markers, and zoom in to that area
    if (allMarkers.size() > 0) {
      Double minLatitude = Collections.min(latitudes);
      Double maxLatitude = Collections.max(latitudes);
      Double minLongitude = Collections.min(longitudes);
      Double maxLongitude = Collections.max(longitudes);

      LatLng southWest = new LatLng(minLatitude, minLongitude);
      LatLng northEast = new LatLng(maxLatitude, maxLongitude);
      System.out.println("southWest = " + southWest);
      System.out.println("northEast = " + northEast);

      final LatLngBounds allMarkersBound = new LatLngBounds(southWest, northEast);
      map.moveCamera(CameraUpdateFactory.newLatLngBounds(allMarkersBound, 400, 400, 0));
    }
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
      case CREATE_MARKER:
        if (resultCode == Activity.RESULT_OK) {
          LatLng latLng = new LatLng(
              data.getDoubleExtra(LATITUDE, 0.0d),
              data.getDoubleExtra(LONGITUDE, 0.0d));
          String title = data.getStringExtra(TITLE_KEY);
          String description = data.getStringExtra(DESCRIPTION_KEY);
          tripStore.insertMarker(
              getArguments().getLong(TRIP_ID), latLng, title, description);
          Marker marker = map.addMarker(
              new MarkerOptions()
                  .position(latLng)
                  .title(title)
                  .snippet(description) // Should we also display latlng?
                  .draggable(true)
                  .icon(BitmapDescriptorFactory.defaultMarker(
                      BitmapDescriptorFactory.HUE_GREEN))
                  .alpha(0.6f));
          marker.hideInfoWindow();
        }
        break;
      default:
        throw new RuntimeException("Unknown request code: " + requestCode);
    }
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    ((MapActivity) activity).onSectionAttached(
        getArguments().getLong(TRIP_ID));
  }
}
